//from PSID: proportion of people who move from periods 2-3, and proportion who move back home
use "$temp/psid_long_cleaned", clear
keep uniqid statefips birth_state weight age
keep if age<=54

//age groups
gen age_group = 1
replace age_group = 2 if age>=36

//limit to people observed in both age groups
gen count = 1
bys uniqid age_group: egen total_obs = total(count) //times observed for each period
bys uniqid: egen min_obs = min(total_obs) //smaller count of the two
drop if min_obs<6 //observed less than 6 years for either rperiod. Doesn't catch people not observed in a gven period at all; take care of that later.

//modal state in periods 2, 3
bys uniqid age_group: egen state_mode = mode(statefips) //modal state in each pedriod
gen flag_miss = (state_mode == .) 
bys uniqid: egen flag_drop = max(flag_miss)
drop if flag_miss == 1 //drop if missing

//cruedely reshape to wide format
sort uniqid age_group
gen temp = state_mode if age_group==1
bys uniqid: egen state1 = max(temp)
drop temp

gen temp = state_mode if age_group==2
bys uniqid: egen state2 = max(temp)
drop temp

drop if state1 == . | state2 == . //this kills people observed in only one period

//collapse to individual level
collapse (first) birth_state state1 state2 (mean) weight, by(uniqid)
keep uniqid birth_state state1 state2 weight
duplicates drop uniqid, force
drop if birth_state==.

//fraction of movers
gen mig1 = (state1!=birth_state)
gen mig2 = (state1!=state2)
gen mig_home = (state1!=state2 & state2 == birth_state)

//moving statistics
su mig1 [w=weight] //not really comparable; don't worry about this
su mig2 [w=weight] //16% move in between period 1 and 2, so a lot less than in the first phase
local mig2 `r(mean)'
su mig_home [w=weight] if mig2 //among movers: 15.5% are moving back to age-17 state
drop if mig2==.

gen type = 1
replace type = 2 if mig2 & !mig_home
replace type = 3 if mig2 & mig_home 

tab type [aw=weight]

local mighome = 0.0258
use "$temp/moments_withiim", clear
count 
local new = `r(N)' + 2
set obs `new'
local line1 = `r(N)' + 1
local line2 = `r(N)' + 2
//local line3 = `r(N)' + 3
replace moment = `mig2' in `line1'
replace moment = `mighome' in `line2'


export delimited "$model/moments/moments.csv", novarn replace //export





exit